//
//  ZYMeMainVC.m
//  YiLin
//
//  Created by Zyark on 2018/5/29.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYMeMainVC.h"
#import "ZYImageUtils.h"
#import "ZYMeInfoView.h"
#import "ZYLoginMainVC.h"
#import "ZYAboutUsVC.h"
#import "ZYDataModificationVC.h"
#import "ZYHouseListVC.h"
#import "ZYSubAccountListVC.h"
#import "WZLBadgeImport.h"
#import "ZYViewUtils.h"
#import "ZYMessageListVC.h"
#import "ZYCustomerFeedbackVC.h"
#import "ZYHelpCenterVC.h"
#import "ZYUser.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "ZYUserInfoViewModel.h"
#import "ZYDeviceViewModel.h"
#import "ZYMessageViewModel.h"
#import "AppDelegate.h"

#define ME_INFO_VIEW_HEIHGT ZYSCREEN_H * 0.4

@interface ZYMeMainVC ()<UITableViewDelegate,UITableViewDataSource,ZYMeInfoViewDelegate>
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) ZYMeInfoView *meInfoView;
@property(nonatomic,strong) NSArray *imageNameArray;
@property(nonatomic,strong) UIButton *logoutBtn;
@property(nonatomic,strong) UIView *logoutView;
@property(nonatomic,strong) ZYUserInfoViewModel *viewModel;
@property(nonatomic,strong) ZYDeviceViewModel *deviceViewModel;
@property(nonatomic,assign) ZYModeType type;
@property(nonatomic,strong) ZYMessageViewModel *messageViewModel;

/**
 右侧导航栏按钮
 */
@property(nonatomic,strong) UIButton *rightButton;
@end

@implementation ZYMeMainVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [ZYUtils setGradualChangingColor:self.view];
    [self setupMeInfoView];
    [self setupLoginBtn];
    [self setupTableView];
    [self setupBindView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setupLeftButton];
    [self setupRightButton];
    self.tabBarController.tabBar.hidden = NO;
    self.fd_interactivePopDisabled = YES;
    [self.viewModel.userInfoCommand execute:nil];
    [self.messageViewModel.isReadCommand execute:nil];
}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.fd_interactivePopDisabled = NO;
}


#pragma mark -init
-(void)setupBindView{
    @weakify(self)
    [self.viewModel.userInfoCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        @strongify(self);
        ZYUser *user = x;
        self.meInfoView.nickname = user.username;
        self.meInfoView.headUrl = user.headImageUrl;
        [self.tableView reloadData];
    }];
    
    //模式改变
    [self.deviceViewModel.statusChangeCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        [ZYBasicHelper handleErrorMessaeWithError:x message:[NSErrorHelper handleErrorMessage:x] controller:self];
    }];
    [[[self.deviceViewModel.statusChangeCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        [ZYConfig setIsAtHome:self.type == ZYModeTypeHome];//设置是否在家
        [self.meInfoView setupTitle];
    }];
    
    //判断是否有未读消息
    [[[self.messageViewModel.isReadCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        if([x boolValue]){
            [self.rightButton showBadgeWithStyle:WBadgeStyleRedDot value:0 animationType:WBadgeAnimTypeNone];
        }else{
            [self.rightButton clearBadge];
        }
    }];
    [self.messageViewModel.isReadCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        if([[NSErrorHelper handleErrorMessage:x] isEqualToString:LOGIN_FAILURE]){
            //登录失效
            [ZYBasicHelper handleErrorMessaeWithError:x message:nil controller:self];
        }
    }];
}

-(void)setupTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ZYSCREEN_H)];
    [self.view addSubview:_tableView];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.scrollEnabled = NO;
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView reloadData];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

-(void)setupMeInfoView{
    _meInfoView = [[ZYMeInfoView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ME_INFO_VIEW_HEIHGT)];
    _meInfoView.delegate = self;
    ZYUser *user = [ZYConfig userInfo];
    _meInfoView.nickname = user.username;
    _meInfoView.headUrl = user.headImageUrl;
    _meInfoView.modeType = ZYModeTypeHome;
}

-(void)setupLoginBtn{
    UIButton *logoutBtn = [[UIButton alloc] init];
    logoutBtn = [ZYViewUtils setupConfirmBtn];
    [logoutBtn addTarget:self action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];
    _logoutBtn = logoutBtn;
    
    _logoutView = [[UIView alloc] init];
    _logoutView.height = logoutBtn.height + 20;
    _logoutView.width = ZYSCREEN_W;
    [_logoutView addSubview:_logoutBtn];
    _logoutBtn.centerX = _logoutView.centerX;
    _logoutBtn.centerY = _logoutView.centerY;
}

-(void)setupTitle{
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    [_logoutBtn setTitle:[language getStringByKey:LC_ME_MAIN_LOGOUT_BTN_TITLE] forState:UIControlStateNormal];
    [_meInfoView setupTitle];
}


//初始化右侧导航栏
-(void)setupRightButton{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    //设置图片
    UIImage *imageForButton = [UIImage imageNamed:@"ic_me_mainmessage"];
    [button setImage:imageForButton forState:UIControlStateNormal];
    
    button.frame = CGRectMake(0, 0, imageForButton.size.width, imageForButton.size.height);
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    [button addTarget:self action:@selector(goToMessage:) forControlEvents:UIControlEventTouchUpInside];
    _rightButton = button;
    self.navigationItem.rightBarButtonItem = barButtonItem;
//    [self.navigationController.navigationBar addSubview:btn];
}

//初始化左侧导航栏
-(void)setupLeftButton{
    UIButton *button = [[UIButton alloc] init];
    [button setTitle:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_ME_MAIN_CONTROLLER_TITLE] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:20];
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = barButtonItem;
}

-(void)changeLanguage{
    [super changeLanguage];
    [self setupTitle];
    [self setupLeftButton];
}

#pragma mark - TableViewDelegate datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0 || section == 3){
        return 1;
    }
    if(section == 2){
        return 2;
    }
    return 3;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        return ME_INFO_VIEW_HEIHGT;
    }
    if(indexPath.section == 3){
        return self.logoutView.height;
    }
    if(ZYiPhone5_OR_5c_OR_5s || ZYiPhone4_OR_4s){
        return 35;
    }if(ZYiPhone6Plus_OR_6sPlus){
        return 50;
    }
    return 45;
}

//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    if(section == 2){
//        return 20;
//    }
//    if(section == 3){
//        //登录按钮
//        return 5;
//    }
//    return 0;
//}
//
//-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    UIView *view = [[UIView alloc] init];
//    if (section == 2) {
//        view.size = CGSizeMake(ZYSCREEN_W, 20);
//        UIView *line = [[UIView alloc] init];
//        line.size = CGSizeMake(ZYSCREEN_W - 30, 1);
//        line.backgroundColor = RGBA(248, 248, 248, 1);
//        [view addSubview:line];
//        line.centerY = view.height / 2;
//        line.left = 15;
//    }
//    return view;
//}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
    }
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    cell.backgroundColor = [UIColor whiteColor];
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    switch (indexPath.section) {
        case 0:
            [cell addSubview:self.meInfoView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            break;
        case 1:
            //住宅编辑 资料修改 子账户管理
            cell.textLabel.text = @[[language getStringByKey:LC_ME_MAIN_RESIDENTIAL_EDITING],[language getStringByKey:LC_ME_MAIN_DATA_MODIFICATION],[language getStringByKey:LC_ME_MAIN_SUBACCOUNT_MANAGEMENT]][indexPath.row];
            break;
        case 2:
            //帮助中心 用户反馈 关于我们
            cell.textLabel.text = @[
//                                    [language getStringByKey:LC_ME_MAIN_HELP_CENTER],
                                    [language getStringByKey:LC_ME_MAIN_CUSTOMER_FEEDBACK]
                                    ,[language getStringByKey:LC_ME_MAIN_ABOUT_US]
                                    ][indexPath.row];
            break;
        case 3:
            [cell addSubview:self.logoutView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            break;
        default:
            break;
    }
    if(indexPath.section == 1 || indexPath.section == 2){
        NSString *imageName = self.imageNameArray[indexPath.section-1][indexPath.row];
//        UIImage *image = [ZYImageUtils reSizeImage:[UIImage imageNamed:imageName] toSize: CGSizeMake(22, 18)];
        cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
        cell.imageView.image = [UIImage imageNamed:imageName];
    }
   
    return cell;
}

#pragma mark - TableView delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 1){
        if(indexPath.row == 0){
            //住宅编辑
            ZYHouseListVC *vc = [[ZYHouseListVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if(indexPath.row == 1){
            //资料修改
            ZYDataModificationVC *vc = [[ZYDataModificationVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            //子账户管理
            ZYSubAccountListVC *vc = [[ZYSubAccountListVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else if(indexPath.section == 2){
        if(indexPath.row == 0){
            ZYCustomerFeedbackVC *vc = [[ZYCustomerFeedbackVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            //关于我们
            ZYAboutUsVC *vc = [[ZYAboutUsVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
//        if(indexPath.row == 0){
//            //帮助中心
//            ZYHelpCenterVC *vc = [[ZYHelpCenterVC alloc] init];
//            [self.navigationController pushViewController:vc animated:YES];
//        }else if(indexPath.row == 1){
//            //用户反馈
//            ZYCustomerFeedbackVC *vc = [[ZYCustomerFeedbackVC alloc] init];
//            [self.navigationController pushViewController:vc animated:YES];
//        }else{
//            //关于我们
//            ZYAboutUsVC *vc = [[ZYAboutUsVC alloc] init];
//            [self.navigationController pushViewController:vc animated:YES];
//        }
    }
}

#pragma mark - MeInfoViewDelegate
-(void)meInfoView:(ZYMeInfoView *)meInfoView setMode:(ZYModeType)type{
    _type = type;
    self.deviceViewModel.houseId = [[ZYConfig houseId] integerValue];
    [self.deviceViewModel.statusChangeCommand execute:[NSNumber numberWithUnsignedInteger:type]];
}

#pragma mark - Events
- (void)backClick:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)logout{
    [ZYConfig clearUserInfo];
    [self goToLogin];
}

-(void)goToMessage:(id)button{
    ZYMessageListVC *vc = [[ZYMessageListVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

//跳转到登录控制器
-(void)goToLogin{
    [ZYBasicHelper goToLogin:self];
}

#pragma mark - Getter
-(NSArray *)imageNameArray{
    if(!_imageNameArray){
        _imageNameArray = @[@[@"ic_me_main_residential_editing", @"ic_me_main_data_modification",@"ic_me_main_subaccount_management"], @[
//                                @"ic_me_main_help_center",
                                                                                                                                         @"ic_me_main_customer_feedback"
                                                                                                                                         ,@"ic_me_main_about_us"
                                                                                                                                         ]];
    }
    return _imageNameArray;
}

-(ZYUserInfoViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[ZYUserInfoViewModel alloc] init];
    }
    return _viewModel;
}

-(ZYDeviceViewModel *)deviceViewModel{
    if(!_deviceViewModel){
        _deviceViewModel = [[ZYDeviceViewModel alloc] init];
    }
    return _deviceViewModel;
}

-(ZYMessageViewModel *)messageViewModel{
    if(!_messageViewModel){
        _messageViewModel = [[ZYMessageViewModel alloc] init];
    }
    return _messageViewModel;
}
@end
